//
//  Tool.m
//  Jingjibang
//
//  Created by haipeng on 15-3-7.
//  Copyright (c) 2015年 haipeng. All rights reserved.
//

#import "Tool.h"
#import <AVFoundation/AVFoundation.h>
#import <CoreImage/CoreImage.h>
#import <Foundation/Foundation.h>
#import "Images.h"
#import "QiniuSDK.h"
#import "UIImage+Filtering.h"
#import "WFQiniuManager.h"
#define IS_BRIGHTER @"IS_BRIGHTER"
static NSString *ZXQiNiuScope = @"jingjibang";
static NSString *ZXQiNiuAccessKey = @"dXaB1-g-Ly6B9M5VfuG7tFXX0g1A6RO5Emxu-h-R";
static NSString *ZXQiNiuSecretKey = @"MDZDWxB6oLhrvCUTuaL9HP-PaS19jwsytJlK6UBB";

static NSString *QiNiuHost = @"https://img.jingjibang.cn";
@implementation Tool

+ (void)fetchImageURLsImageArray:(NSArray *)images hub:(MBProgressHUD *)hub withCompleteBlock:(void(^)(NSArray *imageURLs))block{
    
    NSLog(@"images is %@", images);
    
    int totalCount = (int)images.count;
    __block int beaginCount = 1;
    for(int i=0; i<images.count; i++){
        Images *image = [images objectAtIndex:i];
        if(!image.url){
        }else{
            beaginCount++;
        }
    }
    
    if(beaginCount == images.count+1){
        block(images);
        [hub hide:YES];
        return;
    }
    
    QNUploadManager *upManager = [[QNUploadManager alloc] init];
    QNUploadOption *option = [[QNUploadOption alloc] initWithMime:nil progressHandler:^(NSString *key, float percent) {
        NSLog(@"提交百分比%f", percent);
    } params:nil checkCrc:NO cancellationSignal:nil];
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    BOOL isBrighter = [[defaults objectForKey:IS_BRIGHTER] boolValue];
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
    for(int i=0 ; i<[images count]; i++){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            Images *imageInEbook = images[i];
            if(imageInEbook.locale && !imageInEbook.url){
                
                dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
                
                ALAssetsLibrary *alLibrary = [[ALAssetsLibrary alloc] init];
                NSURL *setUrl = [NSURL URLWithString:imageInEbook.locale];
                [alLibrary assetForURL:setUrl resultBlock:^(ALAsset *asset) {
                    
                    ALAssetRepresentation *rep = [asset defaultRepresentation];
                    UIImage *image = [UIImage imageWithCGImage:rep.fullResolutionImage scale:1.0 orientation:rep.orientation];
                    
                    CGImageRef imagerEF = [image CGImage];
                    if(isBrighter){
                        imagerEF = [image exposureEnhance];
                    }
                    image = [UIImage imageWithCGImage:imagerEF scale:1 orientation:image.imageOrientation];
                    if(isBrighter) CGImageRelease(imagerEF);
                    
                    CGFloat compression = 0.9f;
                    CGFloat maxCompression = 0.1f;
                    int maxFileSize = 250*1024;
                    __block NSData *imageData = UIImageJPEGRepresentation(image, compression);
                    while([imageData length]>maxFileSize && compression > maxCompression)
                    {
                        compression -= 0.3;
                        if(compression<=0) compression = 0.0001;
                        imageData = nil;
                        imageData = UIImageJPEGRepresentation(image, compression);
                    }
                    
                    hub.labelText = [NSString stringWithFormat:@"正在上传第%i/%i张图片", beaginCount, totalCount];
                    
                    [upManager putData:imageData key:nil token:[WFQiniuManager createTokenWithScope:ZXQiNiuScope accessKey:ZXQiNiuAccessKey secretKey:ZXQiNiuSecretKey itemkey:[WFQiniuManager createitemKey]] complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                        imageData = nil;
                        NSLog(@"token ＝%@＝ ＝%d＝ ＝%@＝",resp,info.statusCode,key);
                        dispatch_async(dispatch_get_main_queue(), ^{
                            beaginCount++;
                            NSString *statusStr = [NSString stringWithFormat:@"正在上传第%i/%i张图片", beaginCount, totalCount];
                            if(info.statusCode == 200){
                                imageInEbook.url = [NSString stringWithFormat:@"http://img.jingjibang.cn/%@", resp[@"key"]];
                                
                            }
                            
                            if(beaginCount==images.count+1){
                                block(images);
                                return;
                            }
                            hub.labelText = statusStr;
                        });
                        dispatch_semaphore_signal(semaphore);
                        
                    } option:option];
                    
                } failureBlock:^(NSError *error) {
                    dispatch_semaphore_signal(semaphore);
                }];
            }
            
        });
        
    }
    
}

+ (BOOL)isAuthCamera{
    
    BOOL isCameraValid = YES;
    
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus != AVAuthorizationStatusAuthorized){
        isCameraValid = NO;
    }
    return isCameraValid;
    
}

+ (NSString *)saveImageToLocalWithImageData:(NSData *)imageData andPath:(NSString *)path{
    
    if(!path || path.length<=0){
        //给path一个默认值
        path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    }
    NSString *date = nil;
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYMMddhhmmSSS"];
    date = [formatter stringFromDate:[NSDate date]];
    NSString *imageNameHeader = [NSString stringWithFormat:@"/IMGR_%i", arc4random()%10000];
    NSString *imageNameComm = [imageNameHeader stringByAppendingString:date];
    NSString *imageName = [NSString stringWithFormat:@"%@.jpg", [path stringByAppendingString:imageNameComm]];
    [imageData writeToFile:imageName atomically:YES];
    
    return imageName;
    
}

+ (NSString *)toJSONStr:(id)theData{
    
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:theData
                                                       options:0
                                                         error:&error];
    
    if ([jsonData length] > 0 && error == nil){
        return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }else{
        return nil;
    }
}

+ (UIImage *)defaultImage {
    static UIImage *defaultImage = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(20.f, 24.f), NO, 0.0f);
        
        [[UIColor whiteColor] setFill];
        [[UIBezierPath bezierPathWithRect:CGRectMake(0, 6, 20, 1.8)] fill];
        [[UIBezierPath bezierPathWithRect:CGRectMake(0, 12, 20, 1.8)] fill];
        [[UIBezierPath bezierPathWithRect:CGRectMake(0, 18, 20, 1.8)] fill];
        
        defaultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
    });
    return defaultImage;
}

+ (BOOL)isPureInt:(NSString *)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return [scan scanInt:&val] && [scan isAtEnd];
}

+ (BOOL)isPureFloat:(NSString *)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    float val;
    return [scan scanFloat:&val] && [scan isAtEnd];
}

+ (BOOL)isNumText:(NSString *)str{
    if(([Tool isPureFloat:str] || [Tool isPureInt:str]) && [str floatValue]>=0){
        return YES;
    }else{
        return NO;
    }
    
}
+ (BOOL)isNumTextCeng:(NSString *)str
{
    if(([Tool isPureFloat:str] || [Tool isPureInt:str])){
        return YES;
    }else{
        return NO;
    }
}
+ (float)heightForLabelWithStr:(NSString *)str width:(float)width fontSize:(float)fontSize{
    
    NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:fontSize]};
    CGSize size = [str boundingRectWithSize:CGSizeMake(width, 0) options: NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading | NSStringDrawingTruncatesLastVisibleLine attributes:attribute context:nil].size;
    return size.height;
    
}

+ (void)alsetWithSetUrls:(NSArray *)setUrls setLibary:(ALAssetsLibrary *)alLibrary withSuccessBlock:(ALSetsSuccessBlock)block{
    
    __block NSMutableArray *assets = [[NSMutableArray alloc] init];
    __block int countTag = 0;
    for(NSString *urlStr in setUrls){
        [alLibrary assetForURL:[NSURL URLWithString:urlStr] resultBlock:^(ALAsset *set){
            [assets addObject:set];
            if(setUrls.count == countTag+1) block(assets);
            countTag++;
        } failureBlock:^(NSError *error) {
            if(setUrls.count == countTag+1) block(assets);
            countTag++;
        }];
    }
    
}

+ (void)alsetWithSetUrl:(NSString *)urlStr setLibary:(ALAssetsLibrary *)alLibrary withSuccessBlock:(ALSingleSetSuccessBlock)block{
    
    [alLibrary assetForURL:[NSURL URLWithString:urlStr] resultBlock:^(ALAsset *set){
        block(set);
    } failureBlock:^(NSError *error) {
        block(nil);
    }];
    
}

+ (NSMutableArray *)alsetUrlWithSets:(NSArray *)sets{
    
    NSMutableArray *urls = [[NSMutableArray alloc] init];
    for(ALAsset *set in sets){
        [urls addObject:[NSString stringWithFormat:@"%@", [set valueForProperty:ALAssetPropertyAssetURL]]];
    }
    return urls;
    
}

#pragma mark --获取设备ID

+ (id)obtainDeviceID{
    
    NSString * const KEY_USERNAME_PASSWORD = @"com.zhp.jingjibang.usernamepassword";
    NSString * const KEY_PASSWORD = @"com.zhp.jingjibang.password";
    NSMutableDictionary *readUserPwd = (NSMutableDictionary *)[self loadKeyChainValueWithKey:KEY_USERNAME_PASSWORD];
    if([readUserPwd isKindOfClass:[NSDictionary class]]){
        return readUserPwd[KEY_PASSWORD];
    }else{
        NSString *identifierStr = @"";
        
        identifierStr = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
        
        NSMutableDictionary *usernamepasswordKVPairs = [NSMutableDictionary dictionary];
        [usernamepasswordKVPairs setObject:identifierStr forKey:KEY_PASSWORD];
        
        //存
        [self save:KEY_USERNAME_PASSWORD data:usernamepasswordKVPairs];
        return identifierStr;
    }
}

+ (void)save:(NSString *)service data:(id)data{
    //Get search dictionary
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
    //Delete old item before add new item
    SecItemDelete((__bridge CFDictionaryRef)keychainQuery);
    //Add new object to search dictionary(Attention:the data format)
    [keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data] forKey:(__bridge id)kSecValueData];
    //Add item to keychain with the search dictionary
    SecItemAdd((__bridge CFDictionaryRef)keychainQuery, NULL);
}

+ (NSMutableDictionary *)getKeychainQuery:(NSString *)service{
    return [NSMutableDictionary dictionaryWithObjectsAndKeys:
            (__bridge id)kSecClassGenericPassword,(__bridge id)kSecClass,
            service, (__bridge id)kSecAttrService,
            service, (__bridge id)kSecAttrAccount,
            (__bridge id)kSecAttrAccessibleAfterFirstUnlock,(__bridge id)kSecAttrAccessible,
            nil];
}

+ (id)loadKeyChainValueWithKey:(NSString *)service{
    
    id ret = nil;
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
    //Configure the search setting
    //Since in our simple case we are expecting only a single attribute to be returned (the password) we can set the attribute kSecReturnData to kCFBooleanTrue
    [keychainQuery setObject:(__bridge id)kCFBooleanTrue forKey:(__bridge id)kSecReturnData];
    [keychainQuery setObject:(__bridge id)kSecMatchLimitOne forKey:(__bridge id)kSecMatchLimit];
    CFDataRef keyData = NULL;
    if (SecItemCopyMatching((__bridge CFDictionaryRef)keychainQuery, (CFTypeRef *)&keyData) == noErr) {
        @try {
            ret = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData *)keyData];
        } @catch (NSException *e) {
            NSLog(@"Unarchive of %@ failed: %@", service, e);
        } @finally {
        }
    }
    if (keyData)
        CFRelease(keyData);
    return ret;
    
}
+(void)MoveView:(UIView *)view To:(CGRect)frame During:(float)time{
    
    // 动画开始
    
    [UIView beginAnimations:nil context:nil];
    
    // 动画时间曲线 EaseInOut效果
    
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    
    // 动画时间
    
    [UIView setAnimationDuration:time];
    
    view.frame = frame;
    
    // 动画结束（或者用提交也不错）
    
    [UIView commitAnimations];
}


@end
